<template>
  <div>
    <TableSearch
      ref="tableSearch"
      :tableBtns="tableBtns"
      :search-path="searchPath"
      :formItemsInline="formItemsInline"
      :columns="columns"
      :tableData="tableData"
      :form="form"
      :rules="rules"
      @handleTableData="handleTableData"
      @reset="reset"
    >
      <template slot="address">
        <el-form-item prop="area">
          <HycAddressCascader ref="area" v-model="form.area" />
        </el-form-item>
      </template>
      <el-table-column label="广告图片" slot="img">
        <template #default="{ row }">
          <el-image
            v-if="row.advertPicId"
            :src="getImgUrl(row)"
            :preview-src-list="[getImgUrl(row)]"
          />
          <div v-else>-</div>
        </template>
      </el-table-column>
    </TableSearch>
  </div>
</template>
<script>
import formatter, { typeMap } from '@/utils/format'
import { getAdverList, deleteAdvert, downOrUpAdvert } from '@/api/activity'
import TableSearch from '@/components/TableSearch'
import HycAddressCascader from '@/components/hycAddressCascader'

export default {
  name: 'advertList',
  components: { TableSearch, HycAddressCascader },
  data() {
    return {
      downloadUrl: '/file-management/file/download',
      tableBtns: [
        {
          label: '新增广告',
          icon: 'el-icon-plus',
          click: this.handleAdd,
          resourceId: '/web/activity-management/advert-management/新增广告',
        },
      ],
      searchPath: '/web/activity-management/advert-management/查询',
      formItemsInline: [
        {
          placeholder: '请输入广告名称',
          type: 'text',
          clearable: true,
          value: 'advertNameLike',
          resourceId: '/web/activity-management/advert-management/广告名称',
        },
        {
          placeholder: '请输入参与电站',
          type: 'text',
          clearable: true,
          value: 'stationNameLike',
          resourceId: '/web/activity-management/advert-management/参与电站',
        },
        {
          slot: 'address',
        },
        {
          type: 'select',
          placeholder: '状态',
          options: typeMap.selectOptions([], 'onlineAdvertStatus'),
          value: 'status',
          resourceId: '/web/activity-management/advert-management/状态',
        },
      ],
      rules: {
        area: [
          {
            validator: (rule, value, callback) => {
              if (this.form.area.province && this.form.stationNameLike) {
                callback(
                  new Error(
                    '仅支持通过【请输入参与电站】和【请选择所在地区】其中一种方式查询，请删除另一种方式中的内容后重试'
                  )
                )
              } else {
                callback()
              }
            },
          },
        ],
        stationNameLike: [
          {
            validator: (rule, value, callback) => {
              if (this.form.area.province && this.form.stationNameLike) {
                callback(
                  new Error(
                    '仅支持通过【请输入参与电站】和【请选择所在地区】其中一种方式查询，请删除另一种方式中的内容后重试'
                  )
                )
              } else {
                callback()
              }
            },
          },
        ],
      },
      columns: [
        {
          slot: 'img',
          resourceId: '/web/activity-management/advert-management/广告图片',
        },
        {
          label: '创建时间',
          prop: 'createTime',
          formatter,
          resourceId: '/web/activity-management/advert-management/创建时间',
        },
        {
          label: '广告名称',
          prop: 'advertName',
          formatter: (row) => {
            if (!row.advertName || row.advertName == '') return '-'
            return row.advertName
          },
          resourceId: '/web/activity-management/advert-management/广告名称',
        },
        {
          label: '链接地址',
          prop: 'advertUrl',
          formatter: (row) => {
            if (!row.advertUrl || row.advertUrl == '') return '-'
            return row.advertUrl
          },
          resourceId: '/web/activity-management/advert-management/链接地址',
        },
        {
          label: '所在地区',
          formatter: (item) => {
            if (item.areaStrList && Array.isArray(item.areaStrList)) {
              return item.areaStrList.join()
            } else {
              return '-'
            }
          },
          resourceId: '/web/activity-management/advert-management/所在地区',
        },
        {
          label: '电站',
          formatter: (item) => {
            let str = ''
            if (!Array.isArray(item.stations)) return '/'
            item.stations.forEach((station) => {
              str += `${station.stationName},`
            })
            str = str.substring(0, str.lastIndexOf(','))

            if (str === '') return '-'

            return str
          },
          resourceId: '/web/activity-management/advert-management/参与电站',
        },
        {
          label: '起止时间',
          formatter: (row) => {
            return (
              typeMap.formatTime(row.advertStart) +
              '  ——  ' +
              typeMap.formatTime(row.advertEnd)
            )
          },
          resourceId: '/web/activity-management/advert-management/起止时间',
        },
        {
          label: '状态',
          prop: 'advertStatus',
          formatter: (row) => {
            return typeMap.onlineAdvertStatus[row.advertStatus] || '/'
          },
          resourceId: '/web/activity-management/advert-management/状态',
        },
        {
          label: '操作',
          resourceId: '/web/activity-management/advert-management/操作',
          buttons: [
            {
              label: '查看详情',
              resourceId: '/web/activity-management/advert-management/广告详情',
              click: (row) => {
                this.$router.push(`/activity/advertDetail/${row.id}`)
              },
            },
            {
              label: '下线',
              resourceId: '/web/activity-management/advert-management/下线',
              class: (row) => {
                if (row.advertStatus !== 'ON_LINE')
                  return 'advertList-button-disabled'
              },
              title: (row) => {
                if (row.advertStatus !== 'ON_LINE')
                  return `只有${typeMap.onlineAdvertStatus['ON_LINE']}的广告才能下线`
                return ''
              },
              click: (row) => {
                if (row.advertStatus !== 'ON_LINE') return

                this.$confirm('是否下线该广告', '提示', {
                  center: true,
                  customClass: 'tip-dialog__wrapper',
                }).then(() => {
                  downOrUpAdvert({ id: row.id, downLine: true })
                    .then(() => {
                      this.$message({
                        type: 'success',
                        showClose: true,
                        message: '下线成功',
                      })

                      this.$refs.tableSearch.refreshTable()
                    })
                    .catch((err) => {
                      console.lot(err)
                    })
                })
              },
            },
            {
              label: '上线',
              resourceId: '/web/activity-management/advert-management/上线',
              class: (row) => {
                if (row.advertStatus !== 'OFF_LINE')
                  return 'advertList-button-disabled'
                return ''
              },
              title: (row) => {
                if (row.advertStatus !== 'OFF_LINE')
                  return `只有${typeMap.onlineAdvertStatus['OFF_LINE']}的广告才能上线`
                return ''
              },
              click: (row) => {
                if (row.advertStatus !== 'OFF_LINE') return

                this.$confirm('是否上线该广告', '提示', {
                  center: true,
                  customClass: 'tip-dialog__wrapper',
                }).then(() => {
                  downOrUpAdvert({ id: row.id, downLine: false })
                    .then(() => {
                      this.$message({
                        type: 'success',
                        showClose: true,
                        message: '上线成功',
                      })

                      this.$refs.tableSearch.refreshTable()
                    })
                    .catch((err) => {
                      console.lot(err)
                    })
                })
              },
            },
            {
              label: '编辑',
              resourceId: '/web/activity-management/advert-management/编辑',
              class: (row) => {
                if (
                  row.advertStatus === 'ON_LINE' ||
                  row.advertStatus === 'FINISH'
                )
                  return 'advertList-button-disabled'
              },
              title: (row) => {
                if (
                  row.advertStatus === 'ON_LINE' ||
                  row.advertStatus === 'FINISH'
                )
                  return (
                    typeMap.onlineAdvertStatus['NOT_ONLINE'] +
                    '和' +
                    typeMap.onlineAdvertStatus['OFF_LINE'] +
                    '的广告才能编辑'
                  )
                return ''
              },
              click: (row) => {
                if (
                  row.advertStatus === 'ON_LINE' ||
                  row.advertStatus === 'FINISH'
                )
                  return
                this.$router.push(`/activity/advertEdit/${row.id}`)
              },
            },
            {
              label: '删除',
              class: (row) => {
                if (row.advertStatus === 'ON_LINE')
                  return 'advertList-button-disabled'
              },
              title: (row) => {
                if (row.advertStatus === 'ON_LINE') return '删除广告前请先下线'
                return ''
              },
              resourceId: '/web/activity-management/advert-management/删除',
              click: (row) => {
                if (row.advertStatus === 'ON_LINE') return

                this.$confirm('是否删除该广告', '提示', {
                  center: true,
                  customClass: 'tip-dialog__wrapper',
                }).then(() => {
                  deleteAdvert({ id: row.id })
                    .then(() => {
                      this.$message({
                        type: 'success',
                        showClose: true,
                        message: '删除成功',
                      })

                      this.$refs.tableSearch.refreshTable()
                    })
                    .catch((err) => {
                      console.lot(err)
                    })
                })
              },
            },
            {
              label: '数据统计',
              resourceId: '/web/activity-management/advert-management/数据统计',
              class: (row) => {
                if (row.advertStatus === 'NOT_ONLINE')
                  return 'advertList-button-disabled'
              },
              title: (row) => {
                if (row.advertStatus === 'NOT_ONLINE')
                  return (
                    typeMap.onlineAdvertStatus['NOT_ONLINE'] +
                    '的广告无数据统计数据'
                  )
                return ''
              },
              click: (row) => {
                if (row.advertStatus === 'NOT_ONLINE') return
                this.$router.push(`/activity/advertStatistics/${row.id}`)
              },
            },
          ],
        },
      ],
      tableData: {},
      form: {
        area: {},
      },
    }
  },
  watch: {
    'form.area'() {
      this.$refs.tableSearch.formValidate()
    },
    'form.stationNameLike'() {
      this.$refs.tableSearch.formValidate()
    },
  },
  methods: {
    handleAdd() {
      this.$router.push('/activity/advertAdd')
    },
    getImgUrl(row) {
      return (
        process.env.VUE_APP_BASE_URL_API +
        (this.downloadUrl ? this.downloadUrl : '/file/img') +
        '?fileId=' +
        row.advertPicId
      )
    },
    handleTableData(params) {
      let validate = true
      if (this.$refs.tableSearch) {
        validate = this.$refs.tableSearch.formValidate()
      }
      if (!validate) return
      params = { ...params, ...this.form.area }
      delete params.area
      getAdverList(params).then((res) => {
        this.tableData = {
          list: res.list,
          totalCount: res.totalAmount,
        }
      })
    },
    reset() {
      this.form = {
        area: {},
      }
    },
  },
}
</script>
<style lang="scss">
.advertList-button-disabled {
  cursor: not-allowed !important;
}
</style>
